<?php
/**
 * 畅捷付接口
 */
namespace changpay;
class ChangPay
{
	
//	鉴权绑卡请求  获取短信
    public function bank1($data){
        $postData = array();	
		// 基本参数
        $postData['Service'] = 'nmg_biz_api_auth_req';
        $postData['Version'] = '1.0';
        $postData['PartnerId'] = $data['PartnerId'];//商户号
//      $postData['PartnerId'] = '200002080023';//商户号
		$postData['InputCharset'] = 'UTF-8';
        $postData['TradeDate'] = date('Ymd').'';
        $postData['TradeTime'] = date('His').'';
		$postData['ReturnUrl'] = 'http://dev.chanpay.com/receive.php';// 前台跳转url
		$postData['Memo'] = '备注';
		// 4.4.2.1. 鉴权绑卡请求（API） 业务参数
        $postData['TrxId'] = date('Ymd') . rand(1, 9) . date('His') . rand(111, 999); //外部流水号
		$postData['MerchantNo'] =$data['PartnerId']; //商户编号，与支付请求接口中SellerId保持一致
		$postData['ExpiredTime'] =   '90m'; //订单有效期，取值范围：1m～48h。单位为分，如1.5h，可转换为90m。用来标识本次鉴权订单有效时间，超过该期限则该笔订单作废
		$postData['MerUserId'] =   $data['MerUserId']; //用户标识
		$postData['BkAcctTp'] =   '01'; //卡类型（00 –银行贷记账户;01 –银行借记账户;）
		$postData['BkAcctNo'] =   $this->rsaEncrypt($data['BkAcctNo']); //卡号
		$postData['IDTp'] =   '01'; //证件类型，01：身份证
		$postData['IDNo'] =   $this->rsaEncrypt($data['IDNo']); //证件号
		$postData['CstmrNm'] =   $this->rsaEncrypt($data['CstmrNm']); //持卡人姓名
		$postData['MobNo'] =   $this->rsaEncrypt($data['MobNo']); //银行预留手机号		
		$postData['CardCvn2'] =   $this->rsaEncrypt(''); //CVV2码，当卡类型为信用卡时必填
		$postData['CardExprDt'] =   $this->rsaEncrypt('08/19'); //有效期，当卡类型为信用卡时必填
		$postData['SmsFlag'] =   '1'; //短信发送标识，0：不发送短信1：发送短信
		$postData['NotifyUrl'] = '';//异步通知地址
		$postData['Extension'] = '';//扩展字段
        $postData['Sign'] = $this->rsaSign($postData);
	    $postData['SignType'] = 'RSA'; //签名类型	
		$query = http_build_query($postData);
		$url = 'https://pay.chanpay.com/mag-unify/gateway/receiveOrder.do?'. $query; //该url为生产环境url
		$jsonstr = $this->httpGet_a($url);
		$json = json_decode($jsonstr,1);
	    return $json;
		
    }
//鉴权绑卡确认接口
public function bank2($data){
        $postData = array();	
		// 基本参数
        $postData['Service'] = 'nmg_api_auth_sms';
        $postData['Version'] = '1.0';
        $postData['PartnerId'] = $data['PartnerId'];//商户号
		$postData['InputCharset'] = 'UTF-8';
        $postData['TradeDate'] = date('Ymd').'';
        $postData['TradeTime'] = date('His').'';
		$postData['ReturnUrl'] = 'http://dev.chanpay.com/receive.php';// 前台跳转url
		$postData['Memo'] = '备注';
		// 4.4.2.3. 鉴权绑卡确认接口（API） 业务参数
        $postData['TrxId'] = date('Ymd') . rand(1, 9) . date('His') . rand(111, 999); //外部流水号
//      $postData['TrxId'] = '1548922432'; //外部流水号
		$postData['OriAuthTrxId'] =$data['OriAuthTrxId']; //填写需要退款的原始订单号
		$postData['SmsCode'] =  $data['SmsCode']; //鉴权短信验证码
		$postData['Extension'] = '';//扩展字段
        $postData['Sign'] = $this->rsaSign($postData);
	    $postData['SignType'] = 'RSA'; //签名类型
		$query = http_build_query($postData);
		$url = 'https://pay.chanpay.com/mag-unify/gateway/receiveOrder.do?'. $query; //该url为生产环境url
		$jsonstr = $this->httpGet_a($url);
		$json = json_decode($jsonstr,1);
	    return $json;
    }
//代付接口
public function payment($data){
        $postData = $needEncryptData = array();
        $needEncryptData['AcctNo'] =$data['AcctNo']; //对手人账号
        $needEncryptData['AcctName'] = $data['AcctName'];
//		p($needEncryptData);
        $needEncryptData = $this->publicRsaSign($needEncryptData);
        $postData['Service'] = 'cjt_dsf';
        $postData['Version'] = '1.0';
        $postData['PartnerId'] = $data['PartnerId'];//商户号
        $postData['TradeDate'] = date('Ymd').'';
        $postData['TradeTime'] = date('His').'';
        $postData['InputCharset'] = 'UTF-8';
        $postData['TransCode'] =  "T10000"; //功能码
        $postData['OutTradeNo'] = date('Ymd') . rand(1, 9) . date('His') . rand(111, 999); //外部流水号
		$postData['BusinessType'] = '1';//业务类型 0私人 1公司
		if(empty($data['BankCommonName'])){
			$data['BankCommonName']='招商银行';
		}
		$postData['BankCommonName'] =$data['BankCommonName'];// 通用银行名称
		$postData['BankCode'] = 'CCB';//对公必填
		$postData['AccountType'] = '00';//账户类型 00借记卡 01贷记卡
		$postData['Currency'] = 'CNY';
		$postData['TransAmt'] = $data['TransAmt'];//交易金额
//		$postData['CorpPushUrl'] = $_SERVER['HTTP_HOST'].'/api.php/index/payment';//商户推送的URL地址
        $postData['CorpPushUrl'] ='http://'.$_SERVER['HTTP_HOST'].'/api.php/Notify/payment';//商户推送的URL地址
		$postData['PostScript'] = '用途';//交易金额
//p($postData);
//p($needEncryptData);die;
        $postData = array_merge($postData, $needEncryptData);
        $postData['Sign']= $this->rsaSign($postData);
        $postData['SignType'] = 'RSA'; //签名类型
//      p($postData);
		$query  =   http_build_query($postData);
        $url     = 'https://pay.chanpay.com/mag-unify/gateway/receiveOrder.do?'.$query;
        $cfg = array(
            'ssl' => true
        );
//		p($url);die;
        $response= $this->curlOpen($url,$cfg);
        $json=json_decode($response,true);
	    return $json;
    }
//银行卡解绑接口
//银行卡号  $bankNo
//用户ID $userId
//商户编号 $MerchantNo
public function jiebang($bankNo,$userId,$MerchantNo){
        $postData = array();	
		// 基本参数
        $postData['Service'] = 'nmg_api_auth_unbind';
        $postData['Version'] = '1.0';
        $postData['PartnerId'] = $MerchantNo;//商户号
		$postData['InputCharset'] = 'UTF-8';
        $postData['TradeDate'] = date('Ymd').'';
        $postData['TradeTime'] = date('His').'';
		$postData['ReturnUrl'] = 'http://dev.chanpay.com/receive.php';// 前台跳转url
		$postData['Memo'] = '备注';

		// 4.4.2.4	鉴权解绑接口（API） 业务参数
        $postData['TrxId'] = date('Ymd') . rand(1, 9) . date('His') . rand(111, 999); //外部流水号
//		$postData['MerchantNo'] =   '200002080023'; //商户编号
        $postData['MerchantNo'] =$MerchantNo; //商户编号

		$postData['MerUserId'] =   $userId; //用户标识
	    $postData['UnbindType'] =   '1'; //解绑模式，0为物理删除，1为逻辑删除
	    $postData['CardBegin'] = substr($bankNo,0,6); //卡号前6位
		$postData['CardEnd'] =  substr($bankNo,-4);//卡号后4位
		$postData['Extension'] = '';//扩展字段

        $postData['Sign'] = $this->rsaSign($postData);
	    $postData['SignType'] = 'RSA'; //签名类型
		
		$query = http_build_query($postData);
		$url = 'https://pay.chanpay.com/mag-unify/gateway/receiveOrder.do?'. $query; //该url为生产环境url
		$jsonstr = $this->httpGet_a($url);
		$json = json_decode($jsonstr,1);
		return $json;
    }
//通过银行卡号  获取银行信息
public function bank_datile($bankNo='',$MerchantNo='200002080023'){
        $postData = $needEncryptData = array();
        $needEncryptData['AcctNo'] = $bankNo; //�������˺�
        $needEncryptData = $this->publicRsaSign($needEncryptData);
        $postData['Service']   =  'cjt_dsf';
        $postData['Version']   =  '1.0';
        $postData['PartnerId']=   $MerchantNo;
        $postData['TradeDate']=   date('Ymd').'';
        $postData['TradeTime']=   date('His').'';
        $postData['InputCharset']= 'UTF-8';
        $postData['TransCode'] =   "C00016"; //������
        $postData['OutTradeNo'] = time(); //�ⲿ��ˮ��
        $postData = array_merge($postData, $needEncryptData);
        $postData['Sign']= $this->rsaSign($postData);
        $postData['SignType'] = 'RSA'; //ǩ������
        $query  =   http_build_query($postData);
        $url     = 'https://pay.chanpay.com/mag-unify/gateway/receiveOrder.do?'.$query;
        $cfg = array(
            'ssl' => true
        );
//      echo '<meta charset="utf-8">';
        $response= $this->curlOpen($url,$cfg);
        $json=json_decode($response,true);
		return $json;
    }
  /**
     * 功能：加密
     * @param $args 加密原文数组
     * return 密文数组
     */
    public function publicRsaSign($args) {
//      $args=array_filter($args);//过滤掉空值
//      $path   =   $this->rsa_public_key;  //私钥地址   需要改成你自己的私钥位置
        $path   =  "./rsa_public_key.pem";  //公钥地址
        $public_key= file_get_contents($path);
        foreach($args as $k=>$v){
            openssl_public_encrypt($v,$encryptStr,$public_key);
            $args[$k] = base64_encode($encryptStr);
        }
        return $args;
    }

/*
     * 功能：通讯
     */

 public function curlOpen ($url, $cfg)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        if ($cfg['ssl']) {
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        }
        curl_setopt($ch,CURLINFO_HEADER_OUT,true);
        $result = curl_exec($ch);
        $info = curl_getinfo($ch);
        curl_close($ch);

        return $result;
    }
    public function rsaSign($args) {
        $args=array_filter($args);//过滤掉空值
	    ksort($args);
	    $query  =   '';
	    foreach($args as $k=>$v){
	        if($k=='SignType'){
	            continue;
	        }
	        if($query){
	            $query  .=  '&'.$k.'='.$v;
	        }else{
	            $query  =  $k.'='.$v;
	        }
	    }
	    //这地方不能用 http_build_query  否则会urlencode
	    //$query=http_build_query($args);
        $path   =   "./rsa_private_key.pem";  //私钥地址
	    $private_key= file_get_contents($path);
	    $pkeyid = openssl_get_privatekey($private_key);
	    openssl_sign($query, $sign, $pkeyid);
	    openssl_free_key($pkeyid);
	    $sign = base64_encode($sign);
	    return $sign;
    }
    
    public function rsaSign2($args) {
        $args=array_filter($args);//过滤掉空值
       $args['SmsFlag']='0';
	    ksort($args);
	    $query  =   '';
	    foreach($args as $k=>$v){
	        if($k=='SignType'){
	            continue;
	        }
	        if($query){
	            $query  .=  '&'.$k.'='.$v;
	        }else{
	            $query  =  $k.'='.$v;
	        }
	    }
	    //这地方不能用 http_build_query  否则会urlencode
	    //$query=http_build_query($args);
        $path   =   "./rsa_private_key.pem";  //私钥地址
	    $private_key= file_get_contents($path);
	    $pkeyid = openssl_get_privatekey($private_key);
	    openssl_sign($query, $sign, $pkeyid);
	    openssl_free_key($pkeyid);
	    $sign = base64_encode($sign);
	    return $sign;
	}

    public function rsaEncrypt($content){	
    	$public_key_path   =   "./rsa_public_key.pem";  //公钥地址 
        $pubKey = file_get_contents($public_key_path);
        $res = openssl_get_publickey($pubKey);
        //把需要加密的内容，按128位拆开解密
        $result  = '';
        for($i = 0; $i < strlen($content)/128; $i++  ) {
            $data = substr($content, $i * 128, 128);
            openssl_public_encrypt ($data, $encrypt, $res);
            $result .= $encrypt;
        }
        $result = base64_encode($result);
        openssl_free_key($res);
        return $result;
    }
    public function httpGet_a($order_url) {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $order_url);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; MSIE 5.01; Windows NT 5.0)');
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
        curl_setopt($ch, CURLOPT_AUTOREFERER, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, "");
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $json = curl_exec($ch);
        curl_close($ch);
        return $json;
    }
    //畅捷直接支付接口   用于银行卡还款   续期  后台代扣
    function changjie_bank($data){
        $postData = array();	
        // 基本参数
        $postData['Service'] = 'nmg_biz_api_quick_payment'; //nmg_biz_api_quick_payment 
        $postData['Version'] = '1.0';
        $postData['PartnerId'] =  $data['PartnerId'];//商户号
		$postData['InputCharset'] = 'UTF-8';
        $postData['TradeDate'] = date('Ymd').'';
        $postData['TradeTime'] = date('His').'';
		$postData['ReturnUrl'] = 'http://xjdd.51xingdai.com/index.php/index/index';// 前台跳转url
		$postData['Memo'] = '备注';
		// 4.4.2.5. 支付请求接口（API） 业务参数
        $postData['TrxId'] =date('His') . rand(111, 999).'/'.$data['OrderSn'].'/'.$data['type']; //外部流水号
		$postData['SellerId'] =    $data['PartnerId']; //商户编号，调用畅捷子账户开通接口获取的子账户编号;该字段可以传入平台id或者平台id下的子账户号;作为收款方使用；与鉴权请求接口中MerchantNo保持一致
		$postData['SubMerchantNo'] =   ''; //子商户，在畅捷商户自助平台申请开通的子商户，用于自动结算
		$postData['ExpiredTime'] =   '90m'; //订单有效期，取值范围：1m～48h。单位为分，如1.5h，可转换为90m。用来标识本次鉴权订单有效时间，超过该期限则该笔订单作废
		$postData['MerUserId'] =   $data['userId']; //用户标识
		$postData['TradeType'] =   '11'; //交易类型（即时 11 担保 12）
		$postData['CardBegin'] = substr($data['BankNo'],0,6); //卡号前6位
		$postData['CardEnd'] = substr($data['BankNo'],-4);//卡号后4位
        $postData['TrxAmt'] =   $data['Money']; //交易金额
		$postData['EnsureAmount'] =   ''; //担保金额
		$postData['SmsFlag'] =   '0'; //短信发送标识,0：不发送短信 1：发送短信		
		$postData['OrdrName'] =   '商品名称'; //商品名称
		$postData['OrdrDesc'] =   ''; //商品详情
		$postData['RoyaltyParameters'] = '';      //"[{'userId':'13890009900','PID':'2','account_type':'101','amount':'100.00'},{'userId':'13890009900','PID':'2','account_type':'101','amount':'100.00'}]"; //退款分润账号集
		$postData['NotifyUrl'] ='http://'.$_SERVER['HTTP_HOST'].'/api.php/Notify/changjie_bank';//商户推送的URL地址
		$postData['Extension'] = '';//扩展字段
        $postData['Sign'] =$this->rsaSign2($postData);
        $postData['SignType'] = 'RSA'; //签名类型	
		$query = http_build_query($postData);
		$url = 'https://pay.chanpay.com/mag-unify/gateway/receiveOrder.do?'. $query; //该url为生产环境url
		$jsonstr = $this->httpGet_a($url);
        $json = json_decode($jsonstr,1);
		return $json;
    }









}
